package com.ctrip.payment.test.powermock;

import com.ckjava.xutils.HttpClientUtils;
import com.ckjava.xutils.http.HttpResult;
import com.ctrip.payment.domain.Task;
import com.ctrip.payment.service.TaskService;
import com.ctrip.payment.util.JsonUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.HashMap;
import java.util.Map;

@RunWith(PowerMockRunner.class)
@PrepareForTest(HttpClientUtils.class) //准备被mock的类，在这里为MathUtil.class
public class MockStatic {

    private TaskService taskService;

    @Before
    public void setUp() {
        taskService = new TaskService();

        //调用PowerMockito.mockStatic()
        PowerMockito.mockStatic(HttpClientUtils.class);

    }

    /**
     * mock HttpClientUtils.get 静态方法的请求和返回
     * @throws Exception
     */
    @Test
    public void loadTaskFromApi() throws Exception {
        // 1. 创建实体对象
        Task t = new Task();
        t.setName("test1");

        HttpResult httpResult = new HttpResult();
        httpResult.setStatusCode(200);
        httpResult.setBodyString(JsonUtils.getMapper().writeValueAsString(t));

        Map<String, String> params = new HashMap<>();
        params.put("name", "test1");

        // 2. 使用 PowerMockito.when()定义mock动作
        PowerMockito.when(HttpClientUtils.get("http://ps.task.com/api", null, params)).thenReturn(httpResult);

        // 3. 调用方法
        Task task1 = taskService.loadTaskFromApi("test1");

        // 4. 验证预期
        Assert.assertTrue(task1.getName().equals(t.getName()));
    }
}
